package com.letfox.redis.util;

import java.util.Map;

import javax.annotation.Resource;

import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class HashOperationUtil<T> {
	
	@Resource(name = "redisTemplate")
	private RedisTemplate<String, T> redisTemplate;
	
	/**
	 * 缓存Map
	 * @param key
	 * @param map
	 * @return
	 */
	public HashOperations<String, String, T> setCacheMap(String key,Map<String, T> map){
		HashOperations<String, String, T> hashOperations = redisTemplate.opsForHash();
		if(map != null){
			for (Map.Entry<String, T> entry : map.entrySet()) {
				hashOperations.put(key,entry.getKey(),entry.getValue());
			}
		}
		return hashOperations;
	}
	
	/**
	 * 获取缓存Map
	 * @param key
	 * @return
	 */
	public Map<String, T> getCacheMap(String key){
		HashOperations<String, String, T> hashOperations = redisTemplate.opsForHash();
		Map<String, T> map = hashOperations.entries(key);
		return map;
	}
	
	/**
	 * 获取缓存Map的值
	 * @param key 域
	 * @param field 字段
	 * @return
	 */
	public T get(String key,String field){
		HashOperations<String, String, T> hashOperations = redisTemplate.opsForHash();
		return hashOperations.get(key, field);
	}
}
